<template>
  <div class="verification-code-container">
    <div class="code-inputs">
      <input
        v-for="(digit, index) in 6"
        :key="index"
        ref="inputRefs"
        v-model="codeArray[index]"
        type="text"
        maxlength="1"
        class="code-input"
        :class="{ 'has-value': codeArray[index] }"
        @input="handleInput($event, index)"
        @keydown="handleKeydown($event, index)"
        @paste="handlePaste"
      />
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import {useTokenStore} from "@/stores/token";
import router from "@/router";

onMounted(()=>{
  if(useTokenStore().hasToken){
    router.push('/center/findStock')
  }
});
// eslint-disable-next-line
const emit = defineEmits(['update:modelValue', 'complete'])

const codeArray = ref(['', '', '', '', '', ''])
const inputRefs = ref([])

// 监听输入变化
watch(codeArray, (newValue) => {
  const code = newValue.join('')
  emit('update:modelValue', code)
  
  // 当所有框都填满时触发完成事件
  if (newValue.every(digit => digit !== '')) {
    emit('complete', code)
  }
}, { deep: true })

// 处理输入
const handleInput = (event, index) => {
  const value = event.target.value
  if (value && index < 5) {
    inputRefs.value[index + 1].focus()
  }
}

// 处理键盘事件
const handleKeydown = (event, index) => {
  if (event.key === 'Backspace' && !codeArray.value[index] && index > 0) {
    inputRefs.value[index - 1].focus()
  }
}

// 处理粘贴
const handlePaste = (event) => {
  event.preventDefault()
  const pastedData = event.clipboardData.getData('text').slice(0, 6)
  const digits = pastedData.split('')
  
  digits.forEach((digit, index) => {
    if (index < 6) {
      codeArray.value[index] = digit
    }
  })
  
  if (digits.length === 6) {
    inputRefs.value[5].focus()
  }
}
</script>

<style lang="scss" scoped>
.verification-code-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.code-inputs {
  display: flex;
  gap: 12px;
}

.code-input {
  width: 45px;
  height: 45px;
  border: 2px solid #dcdfe6;
  border-radius: 12px;
  text-align: center;
  font-size: 20px;
  transition: all 0.3s;
  background-color: #fff;
  
  &:focus {
    border-color: #000;
    outline: none;
    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
  }
  
  &.has-value {
    border-color: #000;
    background-color: #f8f8f8;
  }
}
</style> 